package com.hxci.pointmap.service;

import com.hxci.pointmap.dao.LoginDAO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class LoginService {
    public String checkLogin(HttpServletRequest req, HttpServletResponse resp) {
        String resultStr = "fail";
        String errorMessage = "登录失败";
        
        // 获取表单参数
        String loginAccount = req.getParameter("username");
        String loginPwd = req.getParameter("password");
        String captcha = req.getParameter("captcha");
        
        System.out.println("loginAccount:" + loginAccount + " loginPwd:" + loginPwd + " captcha:" + captcha);
        
        // 验证表单参数
        if (loginAccount == null || loginAccount.trim().isEmpty()) {
            errorMessage = "用户名不能为空";
            req.setAttribute("errorMessage", errorMessage);
            return resultStr;
        }
        
        if (loginPwd == null || loginPwd.trim().isEmpty()) {
            errorMessage = "密码不能为空";
            req.setAttribute("errorMessage", errorMessage);
            return resultStr;
        }
        
        // 验证验证码
        HttpSession session = req.getSession();
        String sessionCaptcha = (String) session.getAttribute("captcha");
        
        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
            errorMessage = "验证码错误";
            req.setAttribute("errorMessage", errorMessage);
            return resultStr;
        }
        
        // 清除session中的验证码，防止重复使用
        session.removeAttribute("captcha");
        
        // 查询用户信息
        String sql = "SELECT * FROM sys_user WHERE login_account = ?";
        List paramList = new ArrayList();
        paramList.add(loginAccount);
        LoginDAO loginDAO = new LoginDAO();
        List<Map<String, Object>> userList = loginDAO.queryUserList(sql, paramList);
        
        if (userList.isEmpty()) {
            errorMessage = "用户不存在";
            req.setAttribute("errorMessage", errorMessage);
            return resultStr;
        }
        
        // 获取数据库中的密码
        Map<String, Object> userMap = userList.get(0);
        String dbPassword = (String) userMap.get("login_pwd");
        
        // 比较密码
        if (!dbPassword.equals(loginPwd)) {
            errorMessage = "密码错误";
            req.setAttribute("errorMessage", errorMessage);
            return resultStr;
        }
        
        // 登录成功，将用户信息存入session
        session.setAttribute("user", userMap);
        session.setAttribute("userId", userMap.get("id"));
        session.setAttribute("userName", userMap.get("user_name"));
        session.setAttribute("loginAccount", userMap.get("login_account"));
        
        resultStr = "success";
        return resultStr;
    }
}
